package com.xiaofeng.pochi.controller;

import com.xiaofeng.pochi.common.Page;
import com.xiaofeng.pochi.common.Result;
import com.xiaofeng.pochi.enums.ResultEnums;
import com.xiaofeng.pochi.mapper.SysRoleMapper;
import com.xiaofeng.pochi.mapper.SysUserRoleMapper;
import com.xiaofeng.pochi.pojo.LoginUser;
import com.xiaofeng.pochi.pojo.SysRole;
import com.xiaofeng.pochi.pojo.SysUser;
import com.xiaofeng.pochi.pojo.SysUserRole;
import com.xiaofeng.pochi.pojo.vo.SysUserVo;
import com.xiaofeng.pochi.pojo.vo.TokenVo;
import com.xiaofeng.pochi.service.SysRoleService;
import com.xiaofeng.pochi.service.SysUserService;
import com.xiaofeng.pochi.shiro.SysUserRealm;
import com.xiaofeng.pochi.shiro.UserToken;
import com.xiaofeng.pochi.utils.IdWorker;
import com.xiaofeng.pochi.utils.ShiroUtils;
import com.xiaofeng.pochi.utils.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.io.Serializable;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Created with IntelliJ IDEA
 *
 * @Author: chc
 * @Date: 2022/07/22/22:07
 * @Description:
 */
@RestController
@RequestMapping("/sysUser")
public class SysUserController {


    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Autowired
    private SysRoleMapper sysRoleMapper;
    @Autowired
    private IdWorker idWorker;


    /**
     * 保存用户
     *
     * @param sysUser
     * @return
     */
    @PostMapping("/save")
    public Result<?> save(@RequestBody SysUserVo sysUser) {
        // 参数校验
        if (StringUtils.isBlank(sysUser.getUsername())) {
            return new Result<>(ResultEnums.PARAMS_NULL, "用户名不能为空！");
        }
        if (StringUtils.isBlank(sysUser.getPassword())) {
            return new Result<>(ResultEnums.PARAMS_NULL, "密码不能为空");
        }
        //保存用户信息
        //拷贝属性
        SysUser user = new SysUser();
        BeanUtils.copyProperties(sysUser,user);
        // id用雪花算法生成
        long userId = idWorker.nextId();
        //根据雪花算法生成id
        sysUser.setId(userId);
        sysUserService.save(user);
        // 如果角色id存在，存入用户角色表
        if (sysUser.getSysRole() != null && sysUser.getSysRole().getRoleId() != null) {
            SysUserRole sysUserRole = new SysUserRole();
            sysUserRole.setUserId(userId);
            sysUserRole.setRoleId(sysUser.getSysRole().getRoleId());
            sysUserRoleMapper.insert(sysUserRole);
        }
        return new Result<>("添加成功");
    }

    /**
     * 修改用户
     * 修改接口一般不提供密码修改功能
     *
     * @param sysUser
     * @return
     */
    @RequestMapping(value = "/update", method = RequestMethod.PUT)
    @RequiresPermissions("sys:user:update")
    public Result<?> update(@RequestBody SysUserVo sysUser) throws InvocationTargetException, IllegalAccessException {

        sysUserService.updateUser(sysUser);
        return new Result<>("修改成功");
    }

    /**
     * 删除接口
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/delete/{id}", method = RequestMethod.DELETE)
    @RequiresPermissions("sys:user:delete")
    public Result<?> delete(@PathVariable Long id) {

        SysUser sysUser = new SysUser();
        //根据id删除用户
        sysUser.setId(id);
        sysUser.setDeleted(1);
        sysUserService.updateById(sysUser);
        return new Result<>("删除成功");
    }

    /**
     * 启用用户
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/enable/{id}", method = RequestMethod.PUT)
    public Result<?> enable(@PathVariable Long id) {
        sysUserService.enable(id);
        return new Result<>("启用成功");
    }

    /**
     * 封禁用户
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/disable/{id}", method = RequestMethod.PUT)
    public Result<?> disable(@PathVariable Long id) {
        sysUserService.disable(id);
        return new Result<>("禁用成功");
    }

    /**
     * 分页查询
     *
     * @param page
     * @return
     */
    @RequestMapping(value = "/getByPage", method = RequestMethod.POST)
    public Result<Page<SysUser>> getByPage(@RequestBody Page<SysUser> page) {
        page = sysUserService.getByPage(page);
        return new Result<>(page);
    }


    /**
     * 根据id查询
     * @param id
     * @return
     */
    @RequestMapping(value = "/get/{id}", method = RequestMethod.GET)
    public Result<SysUserVo> get(@PathVariable Long id) {
        SysUser user = sysUserService.getById(id);
        //拷贝信息
        SysUserVo sysUserVo = new SysUserVo();
        BeanUtils.copyProperties(user,sysUserVo);
        // 查询角色信息
        List<SysUserRole> sysUserRoleList = sysUserRoleMapper.getByUserId(user.getId());
        if (!CollectionUtils.isEmpty(sysUserRoleList)) {
            // 说明有角色信息，取出角色ID
            List<Long> roleIds = sysUserRoleList.stream().map(SysUserRole::getRoleId).collect(Collectors.toList());
            // 根据角色ID去查询所有的角色信息
            List<SysRole> roleList = sysRoleMapper.getByIds(roleIds);
            if (!CollectionUtils.isEmpty(roleList)) {
                sysUserVo.setSysRole(roleList.get(0));
            }
        }else{
            sysUserVo.setSysRole(new SysRole());
        }
        return new Result<>(sysUserVo);
    }
    /**
     * 登录
     *
     * @param sysUser
     * @return
     */
    @PostMapping("/login")
    public Result<TokenVo> login(@RequestBody SysUser sysUser) {
        // 使用shiro进行登录
        Subject subject = SecurityUtils.getSubject();
        AuthenticationToken authenticationToken = new UserToken(sysUser.getUsername(), sysUser.getPassword(), SysUserRealm.class);
        try {
            subject.login(authenticationToken);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result<>(ResultEnums.LOGIN_PARAM_ERROR);
        }
        // 登录成功
        Serializable sessionId = subject.getSession().getId();
        // 更新登录时间
        sysUserService.updateLoginTime(sysUser.getUsername());
        return new Result<>(new TokenVo(sessionId));
    }

    /**
     * 获取登录用户
     *
     * @return
     */
    @RequestMapping("/info")
    public Result<LoginUser> info() {
        LoginUser loginUser = ShiroUtils.getLoginUser();
        return new Result<>(loginUser);
    }

    /**
     * 退出登录
     *
     * @return
     */
    @RequestMapping("/logout")
    public Result<SysUser> logout() {
        Subject currentUser = SecurityUtils.getSubject();
        currentUser.logout();
        return new Result<>("退出成功");
    }
}
